package com.my.xq.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.my.xq.domain.VoteResultQueryParam;
import com.my.xq.domain.entity.Court;
import com.my.xq.domain.entity.Option;
import com.my.xq.domain.entity.Plan;
import com.my.xq.domain.entity.Plan_Message;
import com.my.xq.domain.entity.Proprietor;
import com.my.xq.domain.entity.VoteResult;
import com.my.xq.repository.CourtRepository;
import com.my.xq.repository.OptionRepository;
import com.my.xq.repository.PlanMessageRepository;
import com.my.xq.repository.PlanRepository;
import com.my.xq.repository.ProprietorRepository;
import com.my.xq.repository.VoteResultRepository;
import com.sskj.core.annotation.ControllerLogExeTime;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@RequestMapping("/vote")
public class VoteServiceImpl {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	VoteResultRepository voteResultRepository;

	@Autowired
	OptionRepository optionRepository;

	@Autowired
	CourtRepository courtRepository;

	@Autowired
	ProprietorRepository proprietorRepository;
	
	@Autowired
	PlanMessageRepository planMessageRepository;
	
	@Autowired
	PlanRepository planRepository;

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/addvoteInfo", method = { RequestMethod.POST })
	@ControllerLogExeTime(description = "添加投票结果信息")
	public void addwjxxInfo(@RequestBody Plan_Message pm) {
		List<VoteResult> vrList=pm.getVrList();
		// 根据业主id和小区id查询这个业主所投票算作多少票,同时在问题选项表里面加上对应票数
		for (int i = 0; i < vrList.size(); i++) {
			VoteResult vr = vrList.get(i);
			vr.setBallot(this.getVoteCount(vr.getProprietorId(), vr.getCourtId()));
			if (vr.getResult() != 1 && vr.getResult() != 2) {
				logger.error("不能正确获取投票结果是赞成还是反对");
				break;
			} else {
				Option o = optionRepository.get(vr.getOptionId());
				if (vr.getResult() == 1) {
					o.setAyes(o.getAyes() + vr.getBallot());
				}
				if (vr.getResult() == 2) {
					o.setNays(o.getNays() + vr.getBallot());
				}
				optionRepository.save(o);
				voteResultRepository.save(vr);
			}
		}
		planMessageRepository.save(pm);
		Plan p=planRepository.get(pm.getPlanId());
		p.setPlanCount(p.getPlanCount()+1);
		planRepository.save(p);
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/findAllPage", method = { RequestMethod.GET })
	@ControllerLogExeTime(description = "查询投票结果信息并分页")
	@ApiOperation(value = "查询问卷选项信息", httpMethod = "GET")
	@ApiImplicitParams({ @ApiImplicitParam(name = "name", value = "姓名", paramType = "form", dataType = "string"),
			@ApiImplicitParam(name = "pageNumber", value = "页号", paramType = "form", dataType = "int"),
			@ApiImplicitParam(name = "pageSize", value = "页的大小", paramType = "form", dataType = "int") })
	public Page<VoteResult> findAllPage(@ApiIgnore VoteResultQueryParam cqp, @ApiIgnore Pageable pageable) {
		Page<VoteResult> page = voteResultRepository.findPage(cqp, pageable);
		return page;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "查询所有投票结果信息", log = false)
	@RequestMapping("/findAll")
	public List<VoteResult> findAll() {
		List<VoteResult> list = voteResultRepository.findAll();
		return list;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "查询一条投票结果信息", log = false)
	@RequestMapping("/findOne")
	public VoteResult findOne(String id) {
		VoteResult court = voteResultRepository.get(id);
		return court;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "根据小区和业主以及方案投票id查询这个方案底下所有问题选项投票结果", log = false)
	@RequestMapping("/findOneByCourtAndPerson")
	public Plan_Message findOneByCourtAndPerson(VoteResult v) {
		List<VoteResult> list=voteResultRepository.findOneByCourtAndPerson(v.getProprietorId(), v.getCourtId(), v.getPlanId());
		List<Plan_Message> pmList=planMessageRepository.findPlanMessageResult(v.getProprietorId(), v.getCourtId(), v.getPlanId());
		Plan_Message pm=null;
		if(pmList.isEmpty()) {
			pm=new Plan_Message();
			pm.setVrList(list);
		}else {
			pm=pmList.get(0);
			pm.setVrList(list);
		}
		return pm;
	}
	
	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "根据小区和业主以及方案投票id查询这个方案底下的业主留言", log = false)
	@RequestMapping("/getLeaveMessage")
	@ApiOperation(value = "根据小区和业主以及方案投票id查询这个方案底下的业主留言", httpMethod = "GET")
	@ApiImplicitParams({ @ApiImplicitParam(name = "pageNumber", value = "页号", paramType = "form", dataType = "int"),
			@ApiImplicitParam(name = "pageSize", value = "页的大小", paramType = "form", dataType = "int") })
	public Page<Plan_Message> getLeaveMessage(VoteResult v,@ApiIgnore Pageable pageable) {
		Page<Plan_Message> pmList = null;
		if (null == v.getCourtId() || "".equals(v.getCourtId())) {
			pmList=planMessageRepository.getLeaveMessage2(v.getProprietorName(),
					v.getPlanId(), pageable);
		} else {
			pmList=planMessageRepository.getLeaveMessage1(v.getCourtId(),
					v.getProprietorName(), v.getPlanId(), pageable);
		}
		List<Plan_Message> list = pmList.getContent();
		for (int i = 0; i < list.size(); i++) {
			Plan_Message vr = list.get(i);
			Court court = courtRepository.get(vr.getCourtId());
			Proprietor p = proprietorRepository.get(vr.getProprietorId());
			if (null != court) {
				vr.setCourtName(court.getName());
			} else {
				logger.error("根据courtId获取courtname发生错误");
			}
			if (null != p) {
				vr.setProprietorName(p.getName());
			} else {
				logger.error("根据proprietorId获取proprietorname发生错误");
			}
		}
		return pmList;
	}
	
	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "删除一条方案的留言", log = false)
	@RequestMapping("/delLeaveMessage")
	public void delLeaveMessage(String id) {
		planMessageRepository.delete(id);
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "根据条件查询投票结果", log = false)
	@RequestMapping("/searchOption")
	@ApiOperation(value = "根据条件查询投票结果", httpMethod = "GET")
	@ApiImplicitParams({ @ApiImplicitParam(name = "pageNumber", value = "页号", paramType = "form", dataType = "int"),
			@ApiImplicitParam(name = "pageSize", value = "页的大小", paramType = "form", dataType = "int") })
	public Page<VoteResult> searchOption(VoteResult v, @ApiIgnore Pageable pageable) {
		Page<VoteResult> page = null;
		if (null == v.getCourtId() || "".equals(v.getCourtId())) {
			page = voteResultRepository.searchOption2(v.getProprietorName(), v.getOptionId(), pageable);
		} else {
			page = voteResultRepository.searchOption1(v.getCourtId(), v.getProprietorName(), v.getOptionId(), pageable);
		}
		List<VoteResult> list = page.getContent();
		for (int i = 0; i < list.size(); i++) {
			VoteResult vr = list.get(i);
			Court court = courtRepository.get(vr.getCourtId());
			Proprietor p = proprietorRepository.get(vr.getProprietorId());
			if (null != court) {
				vr.setCourtName(court.getName());
			} else {
				logger.error("根据courtId获取courtname发生错误");
			}
			if (null != p) {
				vr.setProprietorName(p.getName());
			} else {
				logger.error("根据proprietorId获取proprietorname发生错误");
			}
		}
		return page;
	}

	public Integer getVoteCount(String proprietorId, String courtId) {
		return voteResultRepository.getVoteCount(proprietorId, courtId);
	}

	public List<String> toList(String value, String separator) {
		List<String> result = new ArrayList<String>();
		if (!this.isEmpty(value)) {
			String[] as = value.split(separator);
			for (int i = 0; i < as.length; i++) {
				result.add(as[i]);
			}
		}
		return result;
	}

	public boolean isEmpty(String str) {
		return str == null || str.length() == 0;
	}
}
